package com.css.fxfzypg.modules.dpzs.service.impl;

import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.common.utils.excel.ExcelImportUtil;
import com.css.fxfzypg.common.utils.excel.ExcelResult;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.dpzs.entity.DpzsNum;
import com.css.fxfzypg.modules.dpzs.repository.DpzsRepository;
import com.css.fxfzypg.modules.dpzs.service.DpzsService;
import com.css.fxfzypg.util.PlatformDateUtils;
import com.css.fxfzypg.util.PlatformSessionUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Timestamp;

@Service
@Transactional
public class DpzsServiceImpl implements DpzsService {
    @Value("${image.localDir}")
    private String localDir;
    @Autowired
   private DpzsRepository dpzsRepository;
    @Autowired
    private AttachmentInfoService attachmentInfoService;
    @Override
    public String excelReader(String attachId) throws Exception{
        AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(attachId);
        String attachPath = attachmentInfoEntity.getAttachPath();
        String name = localDir  + attachPath;
        FileInputStream is = new FileInputStream(new File(name));
        ExcelResult excelResult = ExcelImportUtil.readExcelBean(is, DpzsNum.class,1);
        if (excelResult.getData().size() != 0) {
            for (Object datum : excelResult.getData()) {
                DpzsNum entity = (DpzsNum) datum;
                save(entity);
            }
        }
        return excelResult.getMessage();
    }

    private void save(DpzsNum entity) {
        entity.setId(UUIDGenerator.getUUID());
        String userId = PlatformSessionUtils.getUserId();
        Timestamp timestamp = PlatformDateUtils.getCurrentTimestamp();
        entity.setCreateUser(userId);
        entity.setCreateTime(timestamp);
        entity.setDelFlag(YNEnum.N.toString());
        dpzsRepository.delete(userId,timestamp);
        dpzsRepository.save(entity);
    }
}
